package com.actionsoft.demo.controller;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.commons.formfile.model.delegate.FormFile;
import com.actionsoft.bpms.server.bind.annotation.Controller;
import com.actionsoft.bpms.server.bind.annotation.HandlerType;
import com.actionsoft.bpms.server.fs.DCContext;
import com.actionsoft.sdk.local.SDK;
import com.actionsoft.sdk.local.api.BOAPI;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller(type = HandlerType.RESTFUL, apiName = "alumniDetailApi", desc = "校友会详情页接口")
@Path("/xiaoyouhui/api")
public class AlumniDetailController {

    private final BOAPI boApi = SDK.getBOAPI();
    private final ObjectMapper objectMapper = new ObjectMapper();

    // 4.2 校友会详情页的两个接口（资讯+活动）
    @GET
    @Path("/getinfo/by")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getAlumniSummary(
            @QueryParam("boName") String boName,
            @QueryParam("org_id") String orgId,
            @QueryParam("org_name") String orgName) {

        // 参数校验
        if (boName == null || boName.isEmpty()) {
            return Response.status(Response.Status.BAD_REQUEST)
                    .entity("{\"error\":\"boName参数不能为空\"}")
                    .build();
        }

        if (orgId == null || orgId.isEmpty()) {
            return Response.status(Response.Status.BAD_REQUEST)
                    .entity("{\"error\":\"org_id参数不能为空\"}")
                    .build();
        }

        if (orgName == null || orgName.isEmpty()) {
            return Response.status(Response.Status.BAD_REQUEST)
                    .entity("{\"error\":\"org_name参数不能为空\"}")
                    .build();
        }

        // 第一次调用 (获取最新组织资讯)
        if ("BO_EU_1752894680960".equals(boName)) {
            try {
                List<BO> newsList = boApi.query(boName)
                        .addQuery("ORG_NAME =", orgName)
                        .addQuery("ORG_ID =", orgId)
                        .orderBy("ALUMNINEWS_TIME DESC")
                        .list();

                // 取最新的一条
                Map<String, Object> result = new HashMap<>();
                result.put("data", newsList.isEmpty() ? null : convertNewsBo(newsList.get(0)));
                return Response.ok(result).build();
            } catch (Exception e) {
                return handleException(e);
            }
        }
        // 第二次调用 (获取最新组织活动)
        else if ("BO_EU_1752895052880".equals(boName)) {
            try {
                List<BO> activityList = boApi.query(boName)
                        .addQuery("STATUS !=", "未发布")
                        .addQuery("ORG_NAME =", orgName)
                        .addQuery("ORG_ID =", orgId)
                        .orderBy("START_TIME DESC")
                        .list();

                // 取最新的一条
                Map<String, Object> result = new HashMap<>();
                result.put("data", activityList.isEmpty() ? null : convertActivityBo(activityList.get(0)));
                return Response.ok(result).build();
            } catch (Exception e) {
                return handleException(e);
            }
        }
        return Response.status(Response.Status.BAD_REQUEST)
                .entity("{\"error\":\"无效的boName参数\"}")
                .build();
    }

    // 4.2.1 组织咨询列表
    @GET
    @Path("/getinfo/by/news")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getOrgNewsList(
            @QueryParam("org_id") String orgId,
            @DefaultValue("1") @QueryParam("page") int page) {

        // 参数校验
        if (orgId == null || orgId.isEmpty()) {
            return Response.status(Response.Status.BAD_REQUEST)
                    .entity("{\"error\":\"org_id参数不能为空\"}")
                    .build();
        }

        if (page < 1) {
            return Response.status(Response.Status.BAD_REQUEST)
                    .entity("{\"error\":\"page参数必须大于0\"}")
                    .build();
        }

        try {
            // 执行查询（获取全部数据）
            List<BO> allNews = boApi.query("BO_EU_1752894680960")
                    .addQuery("ORG_ID =", orgId)
                    .orderBy("SIGN_UP_START DESC")
                    .list();

            // 手动分页处理
            int total = allNews.size();
            int pageSize = 10;
            int start = (page - 1) * pageSize;

            // 检查起始位置是否超出范围
            if (start >= total) {
                return Response.status(Response.Status.BAD_REQUEST)
                        .entity("{\"error\":\"page参数超出范围\"}")
                        .build();
            }

            int end = Math.min(start + pageSize, total);
            List<BO> newsList = allNews.subList(start, end);

            Map<String, Object> result = new HashMap<>();
            result.put("total", total);
            result.put("page", page);
            result.put("data", convertNewsList(newsList));

            return Response.ok(result).build();
        } catch (Exception e) {
            return handleException(e);
        }
    }

    // 4.2.2 组织活动列表
    @GET
    @Path("/getinfo/by/activities")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getOrgActivitiesList(
            @QueryParam("org_id") String orgId,
            @DefaultValue("1") @QueryParam("page") int page) {

        // 参数校验
        if (orgId == null || orgId.isEmpty()) {
            return Response.status(Response.Status.BAD_REQUEST)
                    .entity("{\"error\":\"org_id参数不能为空\"}")
                    .build();
        }

        if (page < 1) {
            return Response.status(Response.Status.BAD_REQUEST)
                    .entity("{\"error\":\"page参数必须大于0\"}")
                    .build();
        }

        try {
            String sqlWhere = "STATUS=:SA OR STATUS=:SB";
            Map<String, Object> params = new HashMap<>();
            params.put("SA", "进行中");
            params.put("SB", "已结束");
            // 执行查询（获取全部数据）
            List<BO> allActivities = boApi.query("BO_EU_1752895052880")
                    .addQuerySqlWhere(sqlWhere, params)
                    .addQuery("ORG_ID =", orgId)
                    .orderBy("SIGN_UP_START DESC")
                    .list();

            // 手动分页处理
            int total = allActivities.size();
            int pageSize = 10;
            int start = (page - 1) * pageSize;
            System.out.println("1111"+total+","+total);
            // 检查起始位置是否超出范围
            if (start >= total) {
                return Response.status(Response.Status.BAD_REQUEST)
                        .entity("{\"error\":\"page参数超出范围\"}")
                        .build();
            }

            int end = Math.min(start + pageSize, total);
            List<BO> activityList = allActivities.subList(start, end);
            List<Map<String, Object>> result = new ArrayList<>();
            for (BO bo : activityList) {

                String url = buildFileUrl(bo.getId(),"ACTIVITY_COVER");
                Map<String, Object> activity = new HashMap<>();
                activity.put("ACTIVITY_ID", bo.get("ACTIVITY_ID"));
                activity.put("ACTIVITY_NAME", bo.get("ACTIVITY_NAME"));
                activity.put("ACTIVITY_COVER", url);
                activity.put("ACTIVITY_TYPE", bo.get("ACTIVITY_TYPE"));
                activity.put("TOP", bo.get("TOP"));
                activity.put("START_TIME", bo.get("START_TIME"));
                activity.put("LOCATION", bo.get("LOCATION"));
                activity.put("STATUS", bo.get("STATUS"));
                result.add(activity);
            }

            return Response.ok(result).build();
        } catch (Exception e) {
            return handleException(e);
        }
    }

    // 4.2.3 组织简介
    @GET
    @Path("/getinfo/by/profile")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getOrgProfile(@QueryParam("org_id") String orgId) {

        // 参数校验
        if (orgId == null || orgId.isEmpty()) {
            return Response.status(Response.Status.BAD_REQUEST)
                    .entity("{\"error\":\"org_id参数不能为空\"}")
                    .build();
        }

        try {
            List<BO> profileList = boApi.query("BO_EU_XIAOYOUHUIZUZHIXINXI")
                    .addQuery("ORG_ID =", orgId)
                    .list();

            if (profileList.isEmpty()) {
                return Response.status(Response.Status.NOT_FOUND)
                        .entity("{\"error\":\"未找到组织信息\"}")
                        .build();
            }

            // 取第一条
            return Response.ok(convertProfileBo(profileList.get(0))).build();
        } catch (Exception e) {
            return handleException(e);
        }
    }

    // 4.2.4 联系信息
    @GET
    @Path("/getinfo/by/contact")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getOrgContact(@QueryParam("org_id") String orgId) {

        // 参数校验
        if (orgId == null || orgId.isEmpty()) {
            return Response.status(Response.Status.BAD_REQUEST)
                    .entity("{\"error\":\"org_id参数不能为空\"}")
                    .build();
        }

        try {
            List<BO> contactList = boApi.query("BO_EU_XIAOYOUHUIZUZHIXINXI")
                    .addQuery("ORG_ID =", orgId)
                    .list();

            if (contactList.isEmpty()) {
                return Response.status(Response.Status.NOT_FOUND)
                        .entity("{\"error\":\"未找到联系信息\"}")
                        .build();
            }

            // 取第一条
            return Response.ok(convertContactBo(contactList.get(0))).build();
        } catch (Exception e) {
            return handleException(e);
        }
    }

    // 4.2.5 成员列表 获取校友头像链接
    @GET
    @Path("/getinfo/by/members")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getOrgMembers(@QueryParam("org_id") String orgId) {

        // 参数校验
        if (orgId == null || orgId.isEmpty()) {
            return Response.status(Response.Status.BAD_REQUEST)
                    .entity("{\"error\":\"org_id参数不能为空\"}")
                    .build();
        }

        try {
            List<BO> members = boApi.query("BO_EU_XIAOYOUHUIZUZHICHENGYUAN")
                    .addQuery("ORG_ID =", orgId)
                    .addQuery("AUDIT_STATUS =","已通过")
                    .orderBy("CREATE_TIME DESC")
                    .list();

            Map<String, Object> result = new HashMap<>();
            result.put("count", members.size());
            result.put("members", convertMemberList(members));

            return Response.ok(result).build();
        } catch (Exception e) {
            return handleException(e);
        }
    }

    // BO转换辅助方法
    private Map<String, Object> convertNewsBo(BO bo) {
        Map<String, Object> map = new HashMap<>();
        map.put("ACTIVITY_ID", bo.getString("ACTIVITY_ID"));
        map.put("ALUMNINEWS_TITLE", bo.getString("ALUMNINEWS_TITLE"));
        map.put("ALUMNINEWS_TOP", bo.getString("ALUMNINEWS_TOP"));
        map.put("ALUMNINEWS_LINK", bo.getString("ALUMNINEWS_LINK"));
        map.put("ALUMNINEWS_TIME", bo.getString("ALUMNINEWS_TIME"));
        map.put("ORG_NAME", bo.getString("ORG_NAME"));

        // 获取资讯封面链接
        String coverUrl = getCoverUrl(bo.getId(), "ALUMNINEWS_COVER");
        map.put("ALUMNINEWS_COVER", coverUrl);

        return map;
    }

    private Map<String, Object> convertActivityBo(BO bo) throws IOException {
        Map<String, Object> map = new HashMap<>();
        map.put("ACTIVITY_ID", bo.getString("ACTIVITY_ID"));
        map.put("ACTIVITY_NAME", bo.getString("ACTIVITY_NAME"));
        map.put("ACTIVITY_COVER", buildFileUrl(bo.getId(),"ACTIVITY_COVER"));
        map.put("ACTIVITY_TYPE", bo.getString("ACTIVITY_TYPE"));
        map.put("TOP",bo.getString("TOP"));
        map.put("ONLINE",bo.getString("ONLINE"));
        map.put("START_TIME", bo.getString("START_TIME"));
        map.put("LOCATION", bo.getString("LOCATION"));
        map.put("STATUS", bo.getString("STATUS"));

        return map;
    }

    private Map<String, Object> convertProfileBo(BO bo) {
        Map<String, Object> map = new HashMap<>();
        map.put("ORG_ID", bo.getString("ORG_ID"));
        map.put("ORG_NAME", bo.getString("ORG_NAME"));
        map.put("ORG_TYPE", bo.getString("ORG_TYPE"));
        map.put("CREATE_TIME", bo.getString("CREATE_TIME"));
        map.put("DESCRIPTION", bo.getString("DESCRIPTION"));

        // 获取组织图片链接
        String pictureUrl = getCoverUrl(bo.getId(), "ORG_PICTURE");
        map.put("ORG_PICTURE", pictureUrl);

        return map;
    }

    private Map<String, Object> convertContactBo(BO bo) {
        Map<String, Object> map = new HashMap<>();
        map.put("ORG_ID", bo.getString("ORG_ID"));
        map.put("ORG_NAME", bo.getString("ORG_NAME"));
        map.put("ORG_TYPE", bo.getString("ORG_TYPE"));
        map.put("USER_NAME", bo.getString("USER_NAME"));
        map.put("USER_PHONE", bo.getString("USER_PHONE"));
        map.put("USER_EMAIL", bo.getString("USER_EMAIL"));

        // 获取组织图片链接
        String pictureUrl = getCoverUrl(bo.getId(), "ORG_PICTURE");
        map.put("ORG_PICTURE", pictureUrl);

        return map;
    }

    // 成员BO转换方法，头像链接获取
    private Map<String, Object> convertMemberBo(BO bo) {
        Map<String, Object> map = new HashMap<>();
        map.put("MEMBERSHIP_ID", bo.getString("MEMBERSHIP_ID"));
        map.put("ALUMNI_ID", bo.getString("ALUMNI_ID"));
        map.put("ALUMNI_NAME", bo.getString("ALUMNI_NAME"));

        // 获取校友头像链接
        String alumniCoverUrl = getAlumniCoverUrl(bo.getString("ALUMNI_ID"));
        map.put("ALUMNI_COVER", alumniCoverUrl);

        return map;
    }

    // 获取校友头像链接
    private String getAlumniCoverUrl(String alumniId) {
        try {
            // 查询校友信息
            List<BO> alumniList = boApi.query("BO_EU_XIAOYOUXINXI")
                    .addQuery("ALUMNI_ID =", alumniId)
                    .list();

            if (alumniList.isEmpty()) {
                return null;
            }

            BO alumniInfo = alumniList.get(0);
            String boid = alumniInfo.getId();

            // 构建头像链接
            return buildFileUrl(boid, "ALUMNI_COVER");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // 获取封面URL
    private String getCoverUrl(String boid, String field) {
        try {
            return buildFileUrl(boid, field);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // 构建文件URL
    private String buildFileUrl(String boid, String field) throws IOException {
        String sid = createClientSession();
        List<FormFile> files = boApi.getFiles(boid, field);
        if (files == null || files.isEmpty()) {
            return null;
        }
        DCContext context = boApi.getFileDCContext(files.get(0));
        String url = context.getDownloadURL();      // 形如 "./df?sid=xxxxx..."
        url = url.replaceFirst("\\./df\\?sid=[^&]*", "/r/df?sid=" + sid); // 替换 sid
        String baseUrl = "https://xysq.bitzh.edu.cn";
        return baseUrl + url;
    }

    // 创建客户端会话
    private String createClientSession() throws IOException {
        // 使用固定账号创建会话
        String json = SDK.getPortalAPI().createClientSession("admin", "123");
        // 解析JSON获取sid
        return objectMapper.readTree(json).path("data").path("sid").asText();
    }

    private List<Map<String, Object>> convertMemberList(List<BO> bos) {
        return bos.stream()
                .map(this::convertMemberBo)
                .collect(Collectors.toList());
    }

    private List<Map<String, Object>> convertNewsList(List<BO> bos) {
        return bos.stream().map(bo -> {
            Map<String, Object> map = new HashMap<>();
            map.put("ALUMNINEWS_TITLE", bo.getString("ALUMNINEWS_TITLE"));
            map.put("ALUMNINEWS_TOP", bo.getString("ALUMNINEWS_TOP"));
            map.put("ALUMNINEWS_LINK", bo.getString("ALUMNINEWS_LINK"));
            map.put("ALUMNINEWS_TIME", bo.getString("ALUMNINEWS_TIME"));
            map.put("ORG_NAME", bo.getString("ORG_NAME"));

            // 获取资讯封面链接
            String coverUrl = getCoverUrl(bo.getId(), "ALUMNINEWS_COVER");
            map.put("ALUMNINEWS_COVER", coverUrl);

            return map;
        }).collect(Collectors.toList());
    }

    private List<Map<String, Object>> convertActivityList(List<BO> bos) {
        return bos.stream().map(bo -> {
            Map<String, Object> map = new HashMap<>();
            map.put("ACTIVITY_ID", bo.getString("ACTIVITY_ID"));
            map.put("ACTIVITY_NAME", bo.getString("ACTIVITY_NAME"));
            map.put("LOCATION", bo.getString("LOCATION"));
            map.put("SIGN_UP_START", bo.getString("SIGN_UP_START"));

            // 获取活动封面链接
            String coverUrl = getCoverUrl(bo.getId(), "ACTIVITY_COVER");
            map.put("ACTIVITY_COVER", coverUrl);

            return map;
        }).collect(Collectors.toList());
    }

    private Response handleException(Exception e) {
        return Response.serverError()
                .entity("{\"error\":\"系统错误: " + e.getMessage() + "\"}")
                .build();
    }
}